package com.liuhangs.learning.crowd.webui.config;

import com.liuhangs.learning.crowd.webui.security.filter.AdminAuthenticationProcessingFilter;
import com.liuhangs.learning.crowd.webui.security.filter.JWTAuthorizationFilter;
import com.liuhangs.learning.crowd.webui.security.handle.UnauthorizedEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration
        .WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**spring Security配置类
 * @author 11757
 * @DATE 2020/6/18
 */
@Configuration
@EnableWebSecurity //指定为spring Security配置类
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AdminAuthenticationProcessingFilter adminAuthenticationProcessingFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http.authorizeRequests().antMatchers("/login").permitAll()
                .antMatchers("/**").access("@permissionService.hasPermission(request,authentication)")
                .and()
                .formLogin().loginProcessingUrl("/login").usernameParameter("userName")
                .passwordParameter("password").permitAll()
                .and()
                .logout().permitAll()
                .and()
                .csrf().disable();

        // 定义异常返回信息
        http.exceptionHandling().authenticationEntryPoint(new UnauthorizedEntryPoint());

        //增加token校验
        http.addFilterBefore(new JWTAuthorizationFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class);

        //用重写的Filter替换掉原有的UsernamePasswordAuthenticationFilter
        http.addFilterAt(adminAuthenticationProcessingFilter,
                UsernamePasswordAuthenticationFilter.class);

        //增加JWT的Token验证Filter
        //http.addFilter(new JWTAuthorizationFilter(authenticationManager()));
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        //配置密码加密方式，使用BCrypt加密
        return new BCryptPasswordEncoder();
    }
}
